package dao

import (
	"server_cluster/http/http_config"
	"server_cluster/http/model"

	"server_cluster/common/logger"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	gormlogger "gorm.io/gorm/logger"
)

type Dao struct {
	db *gorm.DB
}

func NewDao() (*Dao, error) {
	d := new(Dao)
	// 连接mysql
	var gormLogger gormlogger.Interface = nil
	if http_config.GetConfig().LogSql {
		gormLogger = gormlogger.Default.LogMode(gormlogger.Info)
	}
	db, err := gorm.Open(mysql.Open(http_config.GetConfig().GetDbHost()), &gorm.Config{
		Logger: gormLogger,
	})
	if err != nil {
		logger.Error("mysql connect error: %v", err)
		return nil, err
	}
	d.db = db
	err = d.db.AutoMigrate(new(model.User))
	if err != nil {
		logger.Error("auto migrate error: %v", err)
		return nil, err
	}
	// tableList := []any{new(model.DbGmAccount), new(model.DbGmAccountToken),
	// 	new(model.DbAccount), new(model.DbGmServerConfig), new(model.User)}

	// for _, table := range tableList {
	// 	err = d.db.AutoMigrate(table)
	// 	if err != nil {
	// 		logger.Error("auto create table error: %v", err)
	// 		return nil, err
	// 	}
	// }
	return d, nil
}

func (d *Dao) CloseDao() {
}
